package cn.itcast.p2p20.fragments;


import android.content.Intent;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.squareup.otto.Subscribe;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.itcast.p2p20.R;
import cn.itcast.p2p20.act.MyApplication;
import cn.itcast.p2p20.act.RegisterActivity;
import cn.itcast.p2p20.bean.LoginData;
import cn.itcast.p2p20.bean.UserBean;
import cn.itcast.p2p20.bean.request.LoginRequest;
import cn.itcast.p2p20.bean.response.LoginResponse;
import cn.itcast.p2p20.net.BaseRequest;
import cn.itcast.p2p20.net.SuccessResultCallback;
import cn.itcast.p2p20.safe.BytesHelper;
import cn.itcast.p2p20.safe.DigestAlgorithm;
import cn.itcast.p2p20.utils.Constant;
import cn.itcast.p2p20.utils.Util;

/**
 */
public class LoginFragment extends BaseFragment implements SuccessResultCallback<LoginResponse> {


    @InjectView(R.id.fragment_login_username)
    EditText fragmentLoginUsername;
    @InjectView(R.id.textinputlayout_username)
    TextInputLayout textinputlayoutUsername;
    @InjectView(R.id.fragment_login_password)
    EditText fragmentLoginPassword;
    @InjectView(R.id.textinputlayout_password)
    TextInputLayout textinputlayoutPassword;
    @InjectView(R.id.fragment_login_login)
    Button fragmentLoginLogin;
    @InjectView(R.id.fragment_register)
    TextView fragmentRegister;

    @Override
    protected void initData() {

        showSuccessStateLayout();

        ((MyApplication) mContext.getApplicationContext()).getBus().register(this);

        fragmentLoginUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                String username = s.toString();
                if (username.length() < 6) {

                    textinputlayoutUsername.setError("用户名不能少于6位");
                } else {

                    textinputlayoutUsername.setError("");
                }


            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    @Override
    protected void initView(View childFragmentView) {

        ButterKnife.inject(this, childFragmentView);
    }

    @Override
    protected String getTitle() {
        return null;
    }

    @Override
    protected int getContentLayoutRes() {
        return R.layout.fragment_login;
    }


    @OnClick({R.id.fragment_login_login, R.id.fragment_register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fragment_login_login:

                String username = fragmentLoginUsername.getText().toString().trim();
                String password = fragmentLoginPassword.getText().toString().trim();
                //这个密码有可能是注册界面带过来的加密后的密码，也有可能是在登录界面直接输入的

                //这个密码不是从注册界面带过来已经加密的
                if (password.length() != 32) {

                    password = BytesHelper.toHex(DigestAlgorithm.MD5.encrypt(BytesHelper.toBytes(password), null));
                }

                if (checkUsername(username) && checkPassword(password)) {

                    sendRequest(new LoginRequest(username, password), LoginResponse.class, this);
                }

                break;
            case R.id.fragment_register:

                Intent intent = new Intent(mContext, RegisterActivity.class);
                mContext.startActivity(intent);

                break;
        }
    }

    private boolean checkPassword(String password) {

        if (TextUtils.isEmpty(password)) {

            Util.showToast(mContext, "密码不能为空");
            return false;
        }

        if (password.length() < 6) {

            Util.showToast(mContext, "密码不能少于6位");
            return false;
        }

        return true;
    }

    private boolean checkUsername(String username) {

        if (TextUtils.isEmpty(username)) {

            Util.showToast(mContext, "用户名不能为空");
            return false;
        }

        if (username.length() < 6) {

            Util.showToast(mContext, "用户名不能少于6位");
            return false;
        }

        return true;
    }

    @Override
    public void onSuccessResult(BaseRequest request, LoginResponse response) {

        LoginData loginData = response.data;
        UserBean user = loginData.getUser();

        if (user != null) {

            //通知个人中心界面
            ((MyApplication) mContext.getApplicationContext()).getBus().post(user);

            //返回结果码
            getActivity().setResult(Constant.RESULT_LOGIN_SUCCESS);
            getActivity().finish();
        }
    }


    //得到注册的结果通知
    @Subscribe
    public void onRegister(UserBean userBean) {

        fragmentLoginUsername.setText(userBean.getUsername());
        fragmentLoginPassword.setText(userBean.getPassword());
    }
}
